package com.scu.qingshi.facade.domain.impl;

import cn.hutool.core.date.DateTime;
import com.scu.qingshi.common.enums.ResponseCodeEnum;
import com.scu.qingshi.common.exception.interview.InterviewException;
import com.scu.qingshi.common.response.BaseResponse;
import com.scu.qingshi.domain.interview.event.NodeModifyEvent;
import com.scu.qingshi.domain.interview.param.*;
import com.scu.qingshi.domain.interview.service.InterviewDomainService;
import com.scu.qingshi.facade.domain.InterviewEditorFacade;
import com.scu.qingshi.infrastructure.dao.po.InterviewProcess;
import com.scu.qingshi.infrastructure.dao.po.Node;
import com.scu.qingshi.infrastructure.dao.service.InterviewProcessService;
import com.scu.qingshi.infrastructure.event.EventBusCenter;
import com.scu.qingshi.infrastructure.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.Date;

/**
 * @author qingshi
 */
@Api(tags = "面试流程编辑")
@RestController()
@RequestMapping("/interEditor")
public class InterviewEditorFacadeImpl implements InterviewEditorFacade {

    private final Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    InterviewProcessService interviewProcessService;

    @Autowired
    InterviewDomainService interviewDomainService;

    @Autowired
    EventBusCenter eventBusCenter;

    @ApiOperation(value = "创建面试流程",notes = "节点数不能为0")
    @PostMapping("/create")
    @Override
    public BaseResponse createInterviewProcess(@Valid InterCreateRequest req) throws Exception {

        logger.info("InterCreateRequest = {}",req);

        BaseResponse res = new BaseResponse();

        if (DateUtil.expirationDate(req.getDeadline())){
            throw InterviewException.dateError("面试报名截止时间过期,请将日期滞后");
        }

        InterviewProcess interviewProcess = new InterviewProcess();
        interviewProcess.setInterContent(req.getInterContent());
        // end字段暂时不用
        interviewProcess.setEnd(0);
        interviewProcess.setNodeCount(req.getNodeCount());
        interviewProcess.setPersonLimit(req.getPersonLimit());
        interviewProcess.setOpenId(req.getOpenId());
        interviewProcess.setDeadline(DateUtil.convertTextToDate(req.getDeadline()));
        interviewProcess.setName(req.getName());

        interviewProcessService.save(interviewProcess);

        res.setSuccess(true);
        res.setMsg("创建面试流成功");
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        return res;
    }

    @ApiOperation(value = "添加面试节点")
    @PostMapping("/addNode")
    @Override
    public BaseResponse addNode(AddNodeRequest req) throws Exception {

        logger.info("AddNodeRequest = {}",req);

        BaseResponse res = new BaseResponse();

        // 防止面试节点截止时间在开始时间之前
        if (DateUtil.convertTextToDate(req.getEndTime())
                .compareTo(DateUtil.convertTextToDate(req.getStartTime()))<=0){
            throw InterviewException.dateError("节点的截止日期小于开始日期");
        }

        Node node = new Node();
        node.setInterContent(req.getInterContent());
        node.setEndTime(DateUtil.convertTextToDate(req.getEndTime()));
        node.setStartTime(DateUtil.convertTextToDate(req.getStartTime()));
        node.setInformFail(req.getInformFail());
        node.setInformPass(req.getInformPass());
        node.setInformWay(req.getInformWay());
        node.setInterPlace(req.getInterPlace());
        node.setOnline(req.getIsOnline() ? 1 : 0);
        node.setInterId(req.getInterId());
        try {
            interviewDomainService.addOneNode(node);
        }catch (Exception e){
            throw new Exception("添加节点入库失败, exception = "+e.toString());
        }

        res.setSuccess(true);
        res.setMsg("添加面试节点成功");
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        return res;
    }

    @ApiOperation("发布面试")
    @PostMapping("/publish")
    @Override
    public BaseResponse publishProcess(PublishRequest req) throws InterviewException {
        logger.info("PublishRequest = {}",req);
        BaseResponse res = new BaseResponse();

        interviewDomainService.publish(req);

        res.setSuccess(true);
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        res.setMsg("发布成功");
        return res;
    }


    @ApiOperation("修改面试流程")
    @PostMapping("/modifyProcess")
    @Override
    public BaseResponse modifyProcess(ModifyProcessRequest req) {
        return null;
    }

    @ApiOperation("修改面试节点")
    @PostMapping("/modifyNode")
    @Override
    public BaseResponse modifyNode(ModifyNodeRequest req) throws Exception {

        logger.info("ModifyNodeRequest = {}",req);

        String openId = interviewDomainService.modifyNode(req);

        // 异步通知参与该面试的用户
        eventBusCenter.postEvent(NodeModifyEvent.builder()
                .interId(req.getInterId())
                .nodeId(req.getNodeId())
                .openId(openId)
                .build());


        BaseResponse res = new BaseResponse();
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        res.setMsg("修改成功");
        res.setSuccess(true);
        return res;
    }

//    @ApiOperation("删除面试节点")
//    @DeleteMapping("/deleteNode")
//    @Override
//    public BaseResponse deleteNode(DeleteNodeRequest req) throws Exception{
//        logger.info("DeleteNodeRequest = {}",req);
//        BaseResponse res = new BaseResponse();
//        interviewDomainService.delete(req);
//
//        res.setSuccess(true);
//        res.setCode(ResponseCodeEnum.SUCCESS.name());
//        res.setMsg("删除成功");
//        return res;
//    }

    @ApiOperation("结束面试")
    @DeleteMapping("/closeInterview")
    @Override
    public BaseResponse closeInterview(CloseInterviewRequest req) {

        logger.info("CloseInterviewRequest = {}",req);
        BaseResponse res = new BaseResponse();

        interviewDomainService.close(req);

        res.setSuccess(true);
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        res.setMsg("关闭成功");
        return res;
    }

    @DeleteMapping("/deleteNode")
    @ApiOperation("删除节点")
    @Override
    public BaseResponse deleteNode(Integer interId, Integer nodeId) throws InterviewException {
        logger.info("deleteNode req =[interId: {}, nodeId: {}",interId,nodeId);
        BaseResponse res = new BaseResponse();

        interviewDomainService.deleteNode(interId,nodeId);

        res.setSuccess(true);
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        res.setMsg("删除成功");
        return res;
    }

    @PutMapping("/update")
    @ApiOperation("更新面试简介内容")
    @Override
    public BaseResponse update(UpdateInterviewRequest req) throws ParseException {
        logger.info("UpdateInterviewRequest req ={}",req);
        BaseResponse res = new BaseResponse();

        InterviewProcess process = interviewProcessService.getById(req.getInterId());
        process.setName(req.getInterName());
        process.setDeadline(DateUtil.convertTextToDate(req.getDeadline()));
        process.setNodeCount(req.getNodeCount());
        process.setInterContent(req.getContent());

        interviewProcessService.iUpdate(process);

        res.setSuccess(true);
        res.setCode(ResponseCodeEnum.SUCCESS.name());
        res.setMsg("更新成功");
        return res;
    }


}
